<template>
  <a-row :gutter="24" class="search-row">
    <a-col :span="24">
      <x-card>
        <div slot="content" class="table-page-search-wrapper" ref="myElement">
          <a-form layout="inline" :model="submitInfo" :rules="submitRules">
            <a-row :gutter="48">
              <a-col :span="24">
                <a-form-item style="margin-bottom: 20px; margin-top: -30px">
                  <a-divider orientation="left" style="font-weight: bold; font-size: 18px" class="custom-divider">
                    <a-icon type="profile" style="margin-right: 8px; color:rgb(13, 158, 243)"></a-icon>基本信息
                  </a-divider>
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item label="检查人员" required :labelCol="{ style: 'width:115px' }">
                  <a-input read-only :value="this.userInfo.nickName"></a-input>
                  <a-icon type="getIconType"></a-icon>
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item label="检查时间" required :labelCol="{ style: 'width:115px' }">
                  <date-picker
                    placeholder="选择日期"
                    :defaultValue="moment().subtract(1, 'second')"
                    show-time
                    format="YYYY-MM-DD HH:mm:ss"
                    :showToday="true"
                    @change="onChangeTime"
                    v-model="checkTime"
                    style="width: 100%"/>
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item label="录入时间" required :labelCol="{ style: 'width:115px' }">
                  <a-input
                    read-only
                    v-model="enterTime"
                    format="YYYY-MM-DD HH:mm:ss"
                    style="width: 100%"/>
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item label="违章单位" :loading="treeLoading" required :labelCol="{ style: 'width:115px' }">
                  <a-cascader
                    :style="{ width: selectWidth + 'px' }"
                    ref="orgTree"
                    tree-node-filter-prop="title"
                    :tree-check-strictly="true"
                    :show-search="true"
                    :show-all-levels="false"
                    style="width: 100%"
                    :dropdownStyle="{ maxHeight: 600, overflow: 'auto'}"
                    placeholder="请选择违章单位"
                    allow-clear
                    :options="unitTree"
                    @change="handleOrganNameClick"
                    treeCheckStrictly
                    :rules="[{ required: true, message: '请选择违章单位'}]"
                    :title="submitInfo.organizationName"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item label="作业专业" required prop="workSpecialty" :labelCol="{ style: 'width:115px' }">
                  <a-select allow-clear placeholder="请选择作业专业" v-model="submitInfo.workSpecialty" :rules="[{ required: true, message: '请选择作业专业'}]" style="font-weight: bold;">
                    <a-select-option v-for="(item) in workSpecialData" :key="item.id" :value="item.specialty" @click="chooseWorkSpecialty(item)">{{ item.specialty }}</a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item label="作业项目" required :labelCol="{ style: 'width:115px' }">
                  <a-input v-model="submitInfo.workItem" allow-clear placeholder="请输入作业项目" />
                </a-form-item>
              </a-col>
              <a-col :span="24">
                <a-form-item style="margin-bottom: 20px; margin-top: -20px">
                  <a-divider orientation="left" style="font-weight: bold; font-size: 18px">
                    <a-icon type="bulb" style="margin-right: 8px; color:rgb(13, 158, 243)"></a-icon>关键作业信息
                  </a-divider>
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item label="关键作业类型" :labelCol="{ style: 'width:115px' }">
                  <a-select allow-clear placeholder="请选择关键作业类型" v-model="submitInfo.workType">
                    <a-select-option v-for="(item) in workTypeData" :key="item.id" :value="item.workType" @click="chooseWorkType(item)">{{ item.workType }}</a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item label="关键作业内容" :labelCol="{ style: 'width:115px' }">
                  <a-select
                    :style="{ width: selectWidth + 'px' }"
                    allow-clear
                    placeholder="请选择关键作业内容"
                    :show-search="true"
                    v-model="submitInfo.workContent"
                    style="width: 380px"
                    :title="submitInfo.workContent">
                    <a-select-option v-for="(item) in workContentData" :key="item.id" :value="item.workContent" @click="chooseWorkContent(item)">{{ item.workContent }}</a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item label="作业风险等级" :labelCol="{ style: 'width:115px' }">
                  <a-input v-model="submitInfo.workRisk"/>
                </a-form-item>
              </a-col>
              <a-col :span="24">
                <a-form-item style="margin-bottom: 20px; margin-top: -20px">
                  <a-divider orientation="left" style="font-weight: bold">
                    <a-icon type="user" style="margin-right: 8px; color:rgb(13, 158, 243)"></a-icon>违章人员
                  </a-divider>
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item label="用工性质" required :labelCol="{ style: 'width:115px' }">
                  <a-select allow-clear placeholder="请选择用工性质" v-model="submitInfo.employeeType" @change="handleEmployeeTypeChange">
                    <a-select-option v-for="(item) in employData" :key="item.id" :value="item.item" @click="chooseEmployeeType(item)">{{ item.item }}</a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item label="人员单位" required :labelCol="{ style: 'width:115px' }">
                  <a-input v-model="submitInfo.violationUserDepart" placeholder="请输入违章人员单位" allow-clear/>
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item label="位置区域" required :labelCol="{ style: 'width:115px' }">
                  <a-select allow-clear placeholder="请选择位置区域" :show-search="true" v-model="submitInfo.location">
                    <a-select-option v-for="(item) in locationData" :key="item.id" :value="item.location" @click="chooseLocation(item)">{{ item.location }}</a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item label="违章人员" required :labelCol="{ style: 'width:115px' }">
                  <a-input
                    suffix-icon="down"
                    v-model="submitInfo.violationUserName"
                    @click="showModals"
                    :read-only="readOnly()"
                    allow-clear
                    placeholder="请选择违章人员姓名"/>
                  <a-modal
                    @cancel="handleCancel"
                    :visible="visible"
                    :width="1400"
                    :height="2000"
                  >
                    <choose-people
                      :people-list="peopleList"
                      @cancel="handleCancel"
                      @chooseUser="chooseVioPeople"
                      :userId="submitInfo.violationUserId"
                    />
                    <template #footer>
                      <a-button type="default" @click="handleCancel">取消</a-button>
                    </template>
                  </a-modal>
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item label="工号/身份证号" required :labelCol="{ style: 'width:115px' }" >
                  <a-input v-model="submitInfo.erp" placeholder="请输入工号/身份证号" allow-clear @blur="validateIDCard()"/>
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item label="违章岗位" required :labelCol="{ style: 'width:115px' }">
                  <a-select allow-clear placeholder="请选择违章岗位" v-model="submitInfo.position">
                    <a-select-option v-for="(item) in positionData" :key="item.id" :value="item.position" @click="choosePosition(item)">{{ item.position }}</a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item label="年龄" :labelCol="{ style: 'width:115px' }" required>
                  <a-select allow-clear placeholder="请选择年龄" v-model="submitInfo.age">
                    <a-select-option v-for="(item) in userAgeData" :key="item.id" :value="item.item" @click="chooseAge(item)">{{ item.item }}</a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item label="工龄" :labelCol="{ style: 'width:115px' }" required>
                  <a-select allow-clear placeholder="请选择工龄" v-model="submitInfo.workYears">
                    <a-select-option v-for="(item) in workAgeData" :key="item.id" :value="item.item" @click="chooseWorkYears(item)">{{ item.item }}</a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :span="24">
                <a-form-item style="margin-bottom: 20px; margin-top: -20px">
                  <a-divider orientation="left" style="font-weight: bold; font-size: 18px">
                    <a-icon type="profile" style="margin-right: 8px; color:rgb(13, 158, 243)"></a-icon>违章信息
                  </a-divider>
                </a-form-item>
              </a-col>
              <a-col :span="16">
                <a-form-item label="违章条款" required :labelCol="{ style: 'width:115px' }">
                  <a-select
                    v-model="submitInfo.violationClause"
                    placeholder="请输入关键字段选择违章条款"
                    allow-clear
                    show-search
                    :style="{ width: selectWidth2 + 'px'}"
                    :title="submitInfo.violationClause"
                  >
                    <a-select-option value="无对应条款" @click="noClause()"><b>无对应条款</b></a-select-option>
                    <a-select-option v-for="(item) in vioClauseData" :key="item.generalSpecialtyId" :value="item.description" @click="chooseVioClause(item)">{{ item.description }}</a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :span="6" style="margin-left: 70px;">
                <a-form-item required :read-only="true">
                  <a-radio-group v-model="submitInfo.violationTypeCategory">
                    <a-radio value="通用违章" :style="{ marginLeft: selectWidth>300? '10px' : '-5px' }" class="readonly-radio">通用违章</a-radio>
                    <a-radio value="专业违章" :style="{ marginLeft: selectWidth>300? '10px' : '-5px' }" class="readonly-radio">专业违章</a-radio>
                    <a-radio value="其他" :style="{ marginLeft: selectWidth>300? '10px' : '-5px' }" class="readonly-radio">其他</a-radio>
                  </a-radio-group>
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item label="违章性质" required :labelCol="{ style: 'width:115px' }">
                  <a-select allow-clear placeholder="请选择违章性质" v-model="submitInfo.violationType">
                    <a-select-option v-for="(item) in vioNatureData" :key="item.violationTypeId" :value="item.violationType" @click="chooseDangerType(item)">{{ item.violationType }}</a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item label="记分" :span="6" :labelCol="{ style: 'width:115px' }">
                  <a-input
                    v-model="submitInfo.score"
                    :read-only="isReadonly()"
                    placeholder="请输入记分"/>
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item label="罚款" :span="6" :labelCol="{ style: 'width:115px' }">
                  <a-input
                    v-model="submitInfo.fine"
                    :read-only="isReadonly1()"
                    placeholder="请输入罚款"/>
                </a-form-item>
              </a-col>
              <a-col :span="16">
                <a-form-item label="违章描述" required :labelCol="{ style: 'width:115px' }">
                  <a-textarea
                    v-model="submitInfo.description"
                    allow-clear
                    :rows="2"
                    :span="40"
                    :title="submitInfo.description"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item label="违章类别" required :labelCol="{ style: 'width:115px' }">
                  <a-tree-select
                    v-model="submitInfo.violationCategory"
                    treeNodeFilterProp="title"
                    :show-search="true"
                    :style="{ width: selectWidth + 'px' }"
                    @change="handleVioCategoryClick"
                    :dropdown-style="{ maxHeight: 400, overflow: 'auto' }"
                    placeholder="请选择违章类别"
                    :allow-clear="true"
                    :tree-default-expand-all="false"
                    :tree-data="vioTypeTree"
                    :title="submitInfo.violationCategory"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item label="检查方式" required :labelCol="{ style: 'width:115px' }">
                  <a-select allow-clear placeholder="请选择检查方式" v-model="submitInfo.InspectionMethod">
                    <a-select-option v-for="item in dangerCheckData" :key="item.id" :value="item.item">{{ item.item }}</a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item label="对应要素体系" required :labelCol="{ style: 'width:115px' }">
                  <a-select allow-clear placeholder="对应要素体系" v-model="submitInfo.hseElement">
                    <a-select-option v-for="(item) in hseData" :key="item.id" :value="item.item" @click="chooseHse(item)">{{ item.item }}</a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item label="原因分析" required :labelCol="{ style: 'width:115px' }">
                  <a-select allow-clear placeholder="请选择原因分析" v-model="submitInfo.causeAnalysis">
                    <a-select-option v-for="(item) in analysisData" :key="item.id" :value="item.item" @click="chooseCauseAnalysis(item)">{{ item.item }}</a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item label="对应安全沟通" :labelCol="{ style: 'width:115px' }">
                  <a-select allow-clear placeholder="对应安全沟通" v-model="submitInfo.observeComm">
                    <a-select-option v-for="(item) in observeData" :key="item.id" :value="item.item1 + item.item2 ">{{ item.item1 + item.item2 }}</a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item label="归属部门" required :labelCol="{ style: 'width:115px' }">
                  <a-select allow-clear placeholder="请选择归属部门" v-model="submitInfo.directDepartment">
                    <a-select-option v-for="(item) in departmentData" :key="item.id" :value="item.item" @click="chooseDepartment(item)">{{ item.item }}</a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item label="可能后果" :labelCol="{ style: 'width:115px' }" required>
                  <a-select allow-clear placeholder="请选择可能后果" v-model="submitInfo.potentialConsequence">
                    <a-select-option v-for="(item) in resultData" :key="item.id" :value="item.item" @click="chooseConsequences(item)">{{ item.item }}</a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item label="图片" :labelCol="{ style: 'width:115px' }">
                  <a-upload
                    name="file"
                    list-type="picture-card"
                    :file-list="fileList"
                    :showUploadList="true"
                    data-type="jpg|png|jpeg|JPG|PNG|JPEG"
                    ref="Pics"
                    :before-upload="beforeUpload"
                    @change="handlePicChange"
                    :remove="handleRemove"
                    @preview="handlePreview"
                    :customRequest="customRequest"
                    multiple
                  >
                    <div v-if="showLoader" class="spinner"></div>
                    <div id="container" v-if="fileList.length < 4 && !showLoader">
                      <a-icon type="plus" />
                      <div class="ant-upload-text">上传</div>
                    </div>
                  </a-upload>
                  <a-modal :visible="previewVisible" :footer="null" @cancel="handlePicCancel">
                    <img alt="example" style="width: 100%" :src="previewImage" />
                  </a-modal>
                </a-form-item>
              </a-col>
            </a-row>
            <a-row :gutter="24">
              <a-col :span="8"></a-col>
              <a-col :span="6">
                <a-form-item style="text-align: center; margin-top: 10px">
                  <a-button @click="saveList" type="primary" v-if="hasPerm('hdv_qhse_v_all_insert')" :loading="saving">保存</a-button>
                  <a-button @click="onSubmit2" v-show="hasPerm('company_violation_send')" :loading="saving1">保存并推送数据</a-button>
                </a-form-item>
              </a-col>
              <a-col :span="6">
                <a-form-item style="text-align: center; margin-top: 10px">
                  <a-button @click="onSubmit" type="primary" :disabled="!saved">新增下一条</a-button>
                </a-form-item>
              </a-col>
            </a-row>
            <!-- <a-row :gutter=24></a-row> -->
          </a-form>
        </div>
      </x-card>
    </a-col>
  </a-row>
</template>
<script>

  import { Empty, DatePicker, TreeSelect, Select, Input, Upload, Form, Radio, Alert, Cascader } from 'ant-design-vue'
  // import { vioComparePic } from '@/api/modular/system/QHSEXyViolation'
  import { STable, XCard, XDown, ChoosePeople } from '@/components'
  // import choosePeople from './choosePeople'
  // eslint-disable-next-line no-unused-vars
  import { getDangerCheckType } from '@/api/modular/system/QHSEDangerinsertManager'
  import {
    addViolationInfo,
    getUserAgeList,
    getUnitTree,
    getVioTypeTree,
    getAnalysisList,
    getDepartmentList,
    getResultList,
    getEmployList,
    getWorkSpecialtyList,
    getKeyWorkTypeList,
    getKeyWorkContentList,
    getLocationList,
    getPositionList,
    getWorkAgeList,
    getVioNatureList,
    editViolationInfo,
    getSpecialtyVioClause,
    getSpecialtyVioClauseAssocition,
    getElementList,
    getCommunicateList,
    getViolationUserNameKid,
    searchSpecialtyVioClause
  } from '@/api/modular/system/violationManage'
  import moment from 'moment'
  import Exif from 'exif-js'
  // eslint-disable-next-line no-unused-vars
  // import { getBase64 } from '../../../../utils/util'
  // import { axios } from '../../../../utils/request'
  import { debounce } from 'lodash'
  import TagSelectOption from '@/components/TagSelect/TagSelectOption'
  // eslint-disable-next-line no-unused-vars
  import { mapGetters, mapState } from 'vuex'
  function getBase64 (file) {
    return new Promise((resolve, reject) => {
      const reader = new FileReader()
      reader.readAsDataURL(file)
      reader.onload = () => resolve(reader.result)
      reader.onerror = error => reject(error)
    })
  }
  async function readFileAsync(file) {
    const reader = new FileReader()
    if (file.originFileObj !== undefined) {
      reader.readAsDataURL(file.originFileObj)
      return new Promise((resolve, reject) => {
        reader.onload = function () {
          const base64String = reader.result.split(',')[1]
          resolve({ name: file.name, base64Content: base64String })
        }
        reader.onerror = function () {
          reject(new Error('读取失败'))
        }
      })
    } else {
      const parts = file.url.split(',')
      const base64String = parts[1]
      return { name: file.name, base64Content: base64String }
    }
  }
  async function convertFilesToArrayAsync(files) {
    const outputArray = []
    for (const file of files) {
      const output = await readFileAsync(file)
      // 在这里对输出对象进行进一步处理或者使用
      // console.log('output----', output)
      outputArray.push(output)
    }
    return outputArray
  }
  // 异步加载图片
  function loadImageAsync(file) {
    return new Promise((resolve, reject) => {
      const reader = new FileReader()
      reader.onload = (e) => {
        const image = new Image()
        image.onload = () => resolve(image)
        image.onerror = reject
        image.src = e.target.result
      }
      reader.onerror = reject
      reader.readAsDataURL(file)
    })
  }
  export default {
    name: 'VioInsert',
    components: {
      TagSelectOption,
      XDown,
      XCard,
      STable,
      DatePicker,
      TreeSelect,
      Select,
      Input,
      ChoosePeople,
      Upload,
      Form,
      Radio,
      Alert,
      'a-cascader': Cascader
    },
    props: {
      dataProp: {
        type: Object,
        default: () => ({})
      }
    },
    data() {
      return {
        selectWidth: 200,
        selectWidth2: 200,
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 }
        },
        submitRules: {
          workSpecialty: [
            { required: true, message: '请选择作业专业', trigger: 'blur' }
          ]
        },
        addOrEdit: 0,
        searchWCode: {
          Code: ''
        },
        searchCCode: {
          id: ''
        },
        searchDCode: {
          id: ''
        },
        searchSCode: {
          Code: ''
        },
        age: '',
        flag: true,
        Upload: true,
        previewImage: '',
        previewVisible: false,
        file: {
          name: '',
          base64Content: ''
        },
        fileList: [],
        queryGeneralClause: {},
        queryEleCom: {},
        queryName: {},
        queryClause: {},
        chooseVioCategoryId: '', // 选择的违章类别id
        chooseVioTypeCode: '', // 选择的违章性质code
        chooseWorkTypeCode: '', // 选择的关键作业类型code
        chooseWorkClauseCode: '',
        chooseNameCode: '',
        chooseSpecialtyCode: '', // 选择的作业专业code
        geneOrMajor: '', // 选择的违章类型按钮
        selectedKeys: '',
        nickName: '',
        disabledIds: [], // 存储disabled节点的id
        selectedIds: [], // 存储已选节点的id
        user: {},
        selectedName: null,
        form: this.$form.createForm(this),
        uploadingList: [],
        peopleList: [],
        isUploadDisabled: false,
        readonly: true,
        // 选择的人员
        selectedPerson: {},
        visible: false,
        // dialogVisible: false, // 是否显示选择人员界面
        expandedKeys: [],
        shouldCloseDialog: true,
        isDropdownOpen: false,
        submitInfo: {
          checkOrganizationId: '',
          qhseXyViolationId: '', // 违章id
          check_Type: '', // 检查类型
          checkTypeCode: '', // 检查类型
          userId: '', // 检查人员id
          userName: '', // 检查人员姓名
          checkDate: '', // 检查时间
          enterTime: '', // 录入时间
          enterSys: '公司隐患违章系统', // 数据来源
          organizationId: '', // 违章单位id
          organizationName: '', // 违章单位名
          workItem: '', // 作业项目
          workSpecialty: '钻井专业', // 作业专业
          workSpecialtyCode: 'SP1001', // 作业专业编码
          workType: '', // 关键作业类型
          keyWorkCode: '', // 关键作业类型编码
          workContent: '', // 关键作业内容
          workRisk: '', // 作业风险等级
          location: '', // 位置区域
          locationCode: '', // 位置区域Code
          violationUserId: '', // 违章人员id
          violationUserName: '', // 违章人员姓名
          violationUserDepart: '', // 违章岗位
          erp: '', // ERP号
          position: '', // 违章岗位
          positionCode: '', // 违章岗位Code
          age: '', // 年龄
          ageCode: '', // 年龄Code
          workYears: '', // 工龄
          workYearsCode: '', // 工龄Code
          employeeType: '', // 用工性质
          employeeTypeCode: '', // 用工性质code
          score: 0, // 记分
          fine: 0, // 罚款
          violationTypeCategory: '', // 通用违章 or 专业违章
          violationType: '', // 违章性质
          violationTypeCode: '', // 违章性质Code
          violationClause: undefined, // 违章条款
          description: '', // 违章描述
          violationCategory: '', // 违章类别
          violationCateId: '', // 违章类别Id
          hseElement: '', // 对应要素体系
          hseCode: '', // 对应要素体系Code
          observeComm: '', // 对应安全沟通
          causeAnalysis: '', // 原因分析
          clauseAnalysisCode: '', // 原因分析Code
          directDepartment: '', // 归属部门
          departmentCode: '', // 归属部门Code
          potentialConsequence: '', // 可能后果
          consequencesCode: '', // 可能后果code
          files: [] // 图片文件
        },
        replaceFields: {
          key: 'id'
        },
        treeLoading: true,
        workTypeData: [], // 关键作业类型
        workContentData: [], // 关键作业内容
        vioClauseMData: [],
        workRiskData: [], // 作业风险等级
        workSpecialData: [], // 作业专业
        userAgeData: [], // 年龄
        workAgeData: [], // 工龄
        employData: [], // 用工性质
        unitTree: [], // 违章单位
        positionData: [], // 违章岗位
        processData: [], // 作业工序
        locationData: [], // 位置区域
        elementData: [], // 对应要素体系
        vioNatureData: [], // 违章性质
        vioClauseData: [], // 违章条款
        communicateData: [], // 对应安全沟通
        vioTypeTree: [], // 违章类别
        analysisData: [], // 原因分析
        departmentData: [], // 归属部门
        resultData: [], // 可能后果
        violationCategoryData: [],
        violationTypeData: [],
        scoreData: '',
        fineData: '',
        hseData: [],
        hseFData: [],
        observeFData: [],
        observeData: [],
        violationTypeCategoryData: [],
        ageData: [],
        workYearsData: [],
        employeeTypeData: [],
        PositionData: [],
        dangerCheckData: [],
        name: 'about',
        saving: false,
        saving1: false,
        saved: false,
        // 由于日期控件上绑定的是一个moment对象，所以初始化值要绑定一个undefined/而不是一个空字符串
        myDate: undefined,
        // 查询参数
        queryParam: {},
        showLoader: false, // 显示压缩转圈
        // 加载数据方法 必须为 Promise 对象
        loadData: (parameter) => {

        },
        sexDictTypeDropDown: [],
        statusDictTypeDropDown: [],
        simpleImage: Empty.PRESENTED_IMAGE_SIMPLE,
        data: [],
        fetching: false,
        lastFetchId: 0,
        violationClause: '',
        valId: false, // 身份证号格式校验
        checkTime: null,
        enterTime: null,
        secondOraName: {
          id: ''
        }
      }
    },
    computed: {
      ...mapGetters(['userInfo'])
    },
    async created() {
      try {
        // const date = new Date() // 获取当前日期
        // const year = date.getFullYear() // 获取年份
        // const month = ('0' + (date.getMonth() + 1)).slice(-2) // 获取月份，需要补 0
        // const day = ('0' + date.getDate()).slice(-2) // 获取日期，需要补 0
        // this.submitInfo.checkDate = `${year}-${month}-${day}` // 将日期赋值为年-月-日格式
        this.enterTime = moment(new Date()).format('YYYY-MM-DD HH:mm:ss')
        const tmpTime = moment(this.enterTime).subtract(1, 'second').format('YYYY-MM-DD HH:mm:ss')
        this.submitInfo.enterTime = this.enterTime.replace(' ', 'T')
        this.submitInfo.checkDate = tmpTime.replace(' ', 'T')
        // console.log(this.submitInfo.enterTime)
        // console.log(this.submitInfo.checkDate)
        // this.submitInfo.checkDate = new Date().toLocaleDateString()
        this.submitInfo.userName = this.userInfo.nickName
        this.submitInfo.userId = this.userInfo.id
        this.submitInfo.checkOrganizationId = this.userInfo.currentOrganizationId
        this.submitInfo.secondOrganizationId = this.userInfo.secondOrganizationId
        this.submitInfo.thirdOrganizationId = this.userInfo.thirdOrganizationId
        this.secondOraName.id = this.userInfo.secondOrganizationName
        // 检查方式
        getDangerCheckType(Object.assign(this.queryParam)).then(res => {
          this.dangerCheckData = res.data
        })
        // 获取通用性质列表
        getVioNatureList(Object.assign(this.queryParam)).then(res => {
          this.vioNatureData = res.data
        })
        // 获取作业专业列表
        getWorkSpecialtyList(Object.assign(this.queryParam)).then(res => {
          this.workSpecialData = res.data
        })
        // 获取作业专业为钻井专业的列表
        getKeyWorkTypeList({ 'Code': 'SP1001' }).then(res => {
          this.workTypeData = res.data.rows
        })
        // 获取作业专业为钻井专业的位置区域
        getLocationList({ 'Code': 'SP1001' }).then(res => {
          this.locationData = res.data.rows
        })
        // 获取作业专业为钻井专业的违章岗位
        getPositionList({ 'Code': 'SP1001' }).then(res => {
          this.positionData = res.data.rows
        })
        // 获取年龄列表
        getUserAgeList(Object.assign(this.queryParam)).then(res => {
          this.userAgeData = res.data
        })
        // 获取工龄列表
        getWorkAgeList(Object.assign(this.queryParam)).then(res => {
          this.workAgeData = res.data
        })
        // 获取用工性质列表
        getEmployList(Object.assign(this.queryParam)).then(res => {
          this.employData = res.data
        })
        // 获取原因分析列表
        getAnalysisList(Object.assign(this.queryParam)).then(res => {
          this.analysisData = res.data
        })
        // 获取归属部门列表
        getDepartmentList(Object.assign(this.queryParam)).then(res => {
          this.departmentData = res.data
        })
        // 获取可能后果列表
        getResultList(Object.assign(this.queryParam)).then(res => {
          this.resultData = res.data
        })

        getUnitTree(Object.assign(this.secondOraName)).then(res => {
          this.treeLoading = false
          this.unitTree = this.transformData(res.data)
          if (res.data.length === 0) {
            this.secondOraName.id = '机关总部'
            getUnitTree(Object.assign(this.secondOraName)).then(res => {
              this.unitTree = this.transformData(res.data)
            })
          }
        })
        // 获取违章类别树
        getVioTypeTree(Object.assign(this.queryParam)).then(res => {
          this.treeLoading = false
          this.vioTypeTree = this.formate(res.data)
        })
        // 违章条款
        getSpecialtyVioClause(Object.assign(this.queryParam)).then(res => {
          this.vioClauseData = res.data
          // console.log(res.data)
        })
        this.debouncedFetchVioClause = debounce(this.searchVioClause, 300)
        this.debouncedFetchVioClause('') // 添加这行代码，在组件创建时立即调用一次
      } catch (error) {
        console.error(error)
      }
    },
    beforeDestroy() {
      window.removeEventListener('resize', this.handleResize)
    },
    mounted() {
      this.submitInfo.check_Type = this.dataProp.check_Type
      this.submitInfo.checkTypeCode = this.dataProp.checkTypeCode
      window.addEventListener('resize', this.handleResize)
      this.handleResize()
      // console.log('进入mounted')
      this.setDisabledToParent(this.unitTree)
      // 找出所有拥有子节点的节点并标记为“disabled”
      this.unitTree.forEach((node) => {
        if (node.children) {
          this.disabledIds.push(node.organizationId)
          node.children.forEach((child) => {
            this.disabledIds.push(child.organizationId)
          })
        }
      })
    },
    watch: {
      'violationClause': {
        immediate: true,
        handler() {
          this.data = []
          this.fetching = false
        }
      }
    },
    methods: {
      // 级联单位寻找节点
      transformData(data) {
        function transform(data) {
          return data.map(item => ({
            id: item.id,
            label: item.title, // 将 title 转换为 label
            value: item.value,
            children: item.children ? transform(item.children) : []
          }))
        }
        return transform(data)
      },
      isReadonly() {
        if (this.submitInfo.check_Type === '二级单位-领导检查承包点督导' || this.submitInfo.check_Type === '二级单位-体系审核' || this.submitInfo.check_Type === '二级单位-专项检查' ||
        this.submitInfo.check_Type === '三级单位-领导检查承包点督导' || this.submitInfo.check_Type === '三级单位-专项检查' || this.submitInfo.check_Type === '监督检查-旁站监督检查') {
          return false
        }
        return true
      },
      isReadonly1() {
        if (this.submitInfo.check_Type === '二级单位-领导检查承包点督导' || this.submitInfo.check_Type === '二级单位-体系审核' || this.submitInfo.check_Type === '二级单位-专项检查' ||
        this.submitInfo.check_Type === '三级单位-领导检查承包点督导' || this.submitInfo.check_Type === '三级单位-专项检查' || this.submitInfo.check_Type === '监督检查-驻井监督检查' || this.submitInfo.check_Type === '监督检查-巡回监督检查') {
          return false
        }
        return true
      },
      handleResize() {
        var myElement = this.$refs.myElement
        if (myElement) {
          // var width = myElement.clientWidth
          var width = myElement.offsetWidth
          this.selectWidth = (width - 24 * 4) / 3 - 115
          this.selectWidth2 = width - (width - 24 * 4) / 3 - 115 - 24 * 2
        }
      },
      handleEmployeeTypeChange(value) {
          this.submitInfo.erp = ''
          this.submitInfo.violationUserId = ''
          this.submitInfo.violationUserDepart = ''
          this.submitInfo.violationUserName = ''
          this.submitInfo.age = ''
      },
      validateIDCard() {
        // 正则表达式验证身份证号码格式
        if (this.submitInfo.erp !== '') {
            this.valId = true
            const ageString = this.submitInfo.erp.substring(6, 14)
            const birthDate = moment(ageString, 'YYYYMMDD')
            const age = moment().diff(birthDate, 'years')
            this.age = age
            if (this.age >= 20 && this.age <= 25) {
              this.submitInfo.age = '20-25'
            }
            if (this.age >= 26 && this.age <= 30) {
              this.submitInfo.age = '26-30'
            }
            if (this.age >= 31 && this.age <= 55) {
              this.submitInfo.age = '31-55'
            }
            if (this.age >= 55) {
              this.submitInfo.age = '55以上'
            }
            // console.log(this.submitInfo.age)

            // 只要承包商人员的violationUserId为erp
            if (this.submitInfo.employeeType === '承包商员工' || this.submitInfo.employeeType === '社会化劳务用工') {
              this.submitInfo.violationUserId = this.submitInfo.erp
            }
        } else {
          this.valId = true
        }
      },
      searchVioClause: debounce(function(value) {
        this.lastFetchId += 1
        const fetchId = this.lastFetchId
        this.data = []
        this.fetching = true
        searchSpecialtyVioClause({ 'id': value }).then(response => {
          // console.log('返回的条款123：', response.data)
          if (fetchId !== this.lastFetchId) {
            // for fetch callback order
            return
          }
          const data = response.data.map(item => ({
            label: item.description,
            value: item.generalSpecialtyId
          }))
          this.data = data
          this.fetching = false
        })
        .catch(error => {
          console.error('Error fetching', error)
          this.fetching = false
        })
      }, 300),
      setDisabledToParent(List) {
        // console.log('进入筛选')
        // console.log(List)\\\
        List.forEach((item) => {
          if (item.children && item.children.length > 0) {
            // 递归遍历子节点
            this.setDisabledToParent(item.children)
            // 设置父节点的 disabled 属性
            item.disabled = true
          }
        })
        // console.log(List)
      },
      customRequest(option) {
      },
      getBase64(file) {
        return new Promise((resolve, reject) => {
          const reader = new FileReader()
          reader.readAsDataURL(file)
          reader.onload = () => resolve(reader.result)
          reader.onerror = error => reject(error)
        })
      },
      handleCancel() {
        this.previewVisible = false
        this.visible = false
      },
      async handleChange ({ fileList }) {
        // console.log('进入了handleChange')
        // console.log('fileList=')
        // console.log(fileList)
        this.fileList = fileList
        for (let i = 0; i < fileList.length; i++) {
          this.file.name = fileList[i].name
          const base64code = await this.getBase64(fileList[i].originFileObj)
          this.file.base64Content = base64code.split(',')[1]
          // this.file.base64Content = await this.getBase64(fileList[i].originFileObj)
          // console.log('this.file=')
          // console.log(this.file)
          this.submitInfo.files.push(this.file)
        }
        // console.log(this.submitInfo.files)
      },
      formate(data) {
        return data.map(item => {
          item.value = item.id
          item.key = item.id
          if (item.children) {
            item.children = this.formate(item.children)
          }
          return item
        })
      },
      // 压缩并上传文件
      async compressAndUpload(file) {
        try {
          this.showLoader = true
          const image = await loadImageAsync(file) // 加载图片
          const canvas = document.createElement('canvas')
          const ctx = canvas.getContext('2d')
          // 调整图片尺寸
          const maxWidth = 800
          const maxHeight = 600
          let width = image.width
          let height = image.height
          if (width > maxWidth || height > maxHeight) {
            const ratio = Math.min(maxWidth / width, maxHeight / height)
            width *= ratio
            height *= ratio
          }
          // 根据目标文件大小调整压缩质量
          const maxSizeInBytes = 2 * 1024 * 1024 // 2MB
          let compressedFile = {}
          let quality = 0.9 // 初始压缩质量
          let compressedSize = Infinity
          // 迭代压缩直到文件大小符合要求
          while (compressedSize > maxSizeInBytes && quality > 0) {
            canvas.width = width
            canvas.height = height
            ctx.clearRect(0, 0, width, height)
            ctx.drawImage(image, 0, 0, width, height)
            // 将 canvas 转为 Blob 对象，并获取文件大小
            const blob = await new Promise((resolve) => {
              canvas.toBlob((blob) => {
                resolve(blob)
              }, file.type, quality)
            })
            compressedFile = new File([blob], file.name, {
              type: file.type,
              lastModified: Date.now()
            })
            compressedSize = compressedFile.size
            // 降低压缩质量
            quality -= 0.1
          }
          const uid = 'vc-upload-' + compressedFile.lastModified + '-' + compressedFile.name.split('.')[0]
          compressedFile.uid = uid
          this.showLoader = false
          // console.log('compressedFile', compressedFile)
          return compressedFile // 解析 Promise 并将结果传递出去
        } catch (error) {
          throw error // 如果发生错误，则将错误传递出去
        }
      },
      // 上传图片之前的校验
      async beforeUpload(file) {
        // console.log('这里是 beforeUpload')
        const type = this.$refs.Pics.$attrs['data-type']
        return new Promise((resolve, reject) => {
          // 校验文件类型
          const exName = file.name.split('.')[1]
          if (!type.includes(exName)) {
            this.$message.error('请检查文件类型,只允许上传图片文件')
            const error = new Error('请检查文件类型，只允许上传图片文件')
            reject(error)
          } else if (file.size / 1024 / 1024 > 2) {
            console.log('file:', file)
              this.compressAndUpload(file)
              .then((compressedFile) => {
                // 处理 compressedFile
                // console.log('compressedFile:', compressedFile)
                file = compressedFile
                resolve(file)
              })
              .catch((error) => {
                // 处理错误
                reject(error)
              })
              // const error = new Error('上传文件大小不能超过2MB')
              // reject(error)
          } else {
            let picTime = false
            return new Promise((resolve, reject) => {
              Exif.getData(file, function() {
                const exifData = Exif.getAllTags(this)
                let dateTimeOriginal = exifData.DateTimeOriginal
                const dateTime = exifData.DateTime
                if (!dateTimeOriginal && dateTime) {
                  dateTimeOriginal = dateTime
                }
                if (exifData && dateTimeOriginal) {
                  console.log('dateTimeOriginal', dateTimeOriginal)
                  picTime = true
                } else {
                  picTime = false
                }
                resolve(picTime) // 返回 picTime 的值到 Promise 的 resolve 函数
              })
            }).then(result => {
              resolve(file)
              // if (result) {
              //   // console.log('图片有拍摄时间')
              //   resolve(file)
              //   // 执行图片有拍摄时间时的操作
              // } else {
              //   this.$message.error('该图片没有拍摄时间')
              //   // console.log('图片没有拍摄时间')
              //   // 执行图片没有拍摄时间时的操作
              // }
            }).catch(error => {
              console.error(error)
            })
          }
        })
      },
      // 关闭模态框（图片预览）
      handlePicCancel () {
        this.previewImage = ''
        this.previewVisible = false
      },
      // 打开模态框（图片预览）
      async handlePreview (file) {
        if (!file.url && !file.preview) {
          file.preview = await getBase64(file.originFileObj)
        }
        this.previewImage = file.url || file.preview
        this.previewVisible = true
      },
      // 删除照片
      async handleRemove (file) {
        const index = this.fileList.indexOf(file)
        const newFileList = this.fileList.slice()
        newFileList.splice(index, 1)
        this.fileList = newFileList
        this.flag = false
        const outputArray = await convertFilesToArrayAsync(this.fileList)
        // 最终得到的 outputArray 数组包含多个输出对象
        // 将输出对象数组转换为仅包含 name 和 base64Content 两个属性的数组
        const resultArray = outputArray.map(({ name, base64Content }) => ({
          name,
          base64Content
        }))
        // 最终得到的 resultArray 数组仅包含 name 和 base64Content 两个属性
        this.submitInfo.files = resultArray
      },
      // 上传图片方法handleChange
      async handlePicChange (file) {
        // 当删除的时候会触发onchange事件 因此使用flag控制onchange事件
        if (this.fileList.length >= 4) {
          this.$message.warning('最多只能选择4张图片')
        }
        if (this.flag === true) {
          file.file.status = 'done'
          const formData = new FormData()
          formData.append('file', file.file)
          this.fileList = file.fileList
          // 假设 this.fileList 是包含多个文件对象的数组
          const outputArray = await convertFilesToArrayAsync(this.fileList)
          // 最终得到的 outputArray 数组包含多个输出对象
          // 将输出对象数组转换为仅包含 name 和 base64Content 两个属性的数组
          const resultArray = outputArray.map(({ name, base64Content }) => ({
            name,
            base64Content
          }))
          this.submitInfo.files = resultArray
          // const last = resultArray[resultArray.length - 1]
          // vioComparePic(last).then(res => {
          //   // console.log(res.data)
          //   if (res.data) {
          //     this.$message.error('图片重复')
          //     this.fileList.pop()
          //   } else {
          //     // 最终得到的 resultArray 数组仅包含 name 和 base64Content 两个属性
          //     this.submitInfo.files = resultArray
          //   }
          // })
        } else {
          this.flag = true
        }
      },
      showModals() {
        if (this.submitInfo.employeeType === '承包商员工' || this.submitInfo.employeeType === '社会化劳务用工') {
          this.visible = false
        } else {
          this.visible = true
        }
      },
      readOnly() {
        if (this.submitInfo.employeeType === '承包商员工' || this.submitInfo.employeeType === '社会化劳务用工') {
          return false
        } else {
          return true
        }
      },
      handleDoubleClick() {
        // console.log('双击事件触发')
      },
      // 选择无条款时，为其他
      noClause() {
        this.submitInfo.violationTypeCategory = '其他'
        this.submitInfo.description = '无对应条款'
        this.submitInfo.violationCategory = ''
        this.submitInfo.violationType = ''
        this.submitInfo.score = 0
        this.submitInfo.fine = 0
        this.hseData = []
        this.submitInfo.hseElement = ''
        this.observeData = []
        this.submitInfo.observeComm = ''
        this.submitInfo.violationClause = ''
      },
      // 当选择违章条款时，影响一系列
      chooseVioClause(item) {
        if (item === undefined) {
          this.submitInfo.violationCategory = ''
          this.submitInfo.description = ''
          this.submitInfo.violationType = ''
          this.submitInfo.score = 0
          this.submitInfo.fine = 0
          this.hseData = []
          this.submitInfo.hseElement = ''
          this.observeData = []
          this.submitInfo.observeComm = ''
          this.submitInfo.violationTypeCategory = ''
          this.submitInfo.violationClause = ''
          return
        }
        // this.submitInfo.description = item.label
        // this.chooseWorkClauseCode = item.key
        // this.submitInfo.generalSpecialtyId = item.generalSpecialtyId
        this.submitInfo.description = item.description
        this.chooseWorkClauseCode = item.generalSpecialtyId
        // this.submitInfo.generalSpecialtyId = item.generalSpecialtyId
        this.searchCCode.id = this.chooseWorkClauseCode
        getSpecialtyVioClauseAssocition(Object.assign(this.searchCCode)).then(res => {
          this.submitInfo.vioClauseData = res.data
          // this.submitInfo.violationClause = this.violationClause.label
          this.submitInfo.violationCategory = res.data.violationCategory
          this.submitInfo.violationCateId = res.data.violationCategoryId
          this.submitInfo.violationType = res.data.violationType
          this.submitInfo.violationTypeCode = res.data.violationTypeCode
          if (this.submitInfo.check_Type !== '基层队站-月检查' && this.submitInfo.check_Type !== '基层队站-周检查' && this.submitInfo.check_Type !== '岗位员工检查') {
            this.submitInfo.score = res.data.score
            this.submitInfo.fine = res.data.fine
          }
          this.hseData = res.data.hse
          this.submitInfo.hseElement = this.hseData[0].item
          this.submitInfo.hseCode = this.hseData[0].code
          this.observeData = res.data.observe
          this.submitInfo.observeComm = this.observeData[0].item1 + ';' + this.observeData[0].item2
          this.submitInfo.violationTypeCategory = res.data.violationTypeCategory
          console.log(res.data)
        })
      },
      chooseVioPeople(userName, userId, unitName, employeeNo) {
        // console.log('收到了username=' + userName)
        // console.log('收到了userid=' + userId)
        this.submitInfo.violationUserName = userName
        this.submitInfo.violationUserId = userId
        const parts = unitName.split('/')
        this.submitInfo.violationUserDepart = parts[parts.length - 1]
        this.submitInfo.erp = employeeNo
        this.visible = false
        this.chooseNameCode = this.submitInfo.violationUserId
        this.searchDCode.id = this.chooseNameCode
        getViolationUserNameKid(Object.assign(this.searchDCode)).then(res => {
          this.submitInfo.age = res.data.age ? res.data.age : this.submitInfo.age
          this.submitInfo.ageCode = res.data.ageCode ? res.data.ageCode : this.submitInfo.ageCode
          this.submitInfo.workYears = res.data.workYears ? res.data.workYears : this.submitInfo.workYears
          this.submitInfo.workYearsCode = res.data.workYearsCode ? res.data.workYearsCode : this.submitInfo.workYearsCode
          this.submitInfo.employeeType = res.data.employeeType ? res.data.employeeType : this.submitInfo.employeeType
          this.submitInfo.employeeTypeCode = res.data.employeeTypeCode ? res.data.employeeTypeCode : this.submitInfo.employeeTypeCode
          this.submitInfo.position = res.data.position ? res.data.position : this.submitInfo.position
          this.submitInfo.positionCode = res.data.positionCode ? res.data.positionCode : this.submitInfo.positionCode
          this.submitInfo.erp = res.data.erp ? res.data.erp : this.submitInfo.erp
          console.log('返回数据：', res.data)
        })
        if (this.submitInfo.erp !== null || this.submitInfo.erp !== '') {
          this.valId = true
        }
      },
      // 当选择作业专业时，影响关键作业类型和位置区域
      chooseWorkSpecialty(item) {
        this.chooseSpecialtyCode = item.specialtyCode
        this.submitInfo.workSpecialtyCode = item.specialtyCode
        // 清除现有关键作业类型、位置区域、违章岗位
        this.submitInfo.workType = ''
        this.submitInfo.workContent = ''
        this.submitInfo.workRisk = ''
        this.workTypeData = []
        this.locationData = []
        this.positionData = []
        this.workContentData = []
        // console.log('specialtyCode=' + this.chooseSpecialtyCode)
        this.searchSCode.Code = this.chooseSpecialtyCode
        // 获取关键作业类型
        getKeyWorkTypeList(Object.assign(this.searchSCode)).then(res => {
          this.workTypeData = res.data.rows
        })
        // 获取位置区域
        getLocationList(Object.assign(this.searchSCode)).then(res => {
          this.locationData = res.data.rows
        })
        // 获取违章岗位
        getPositionList(Object.assign(this.searchSCode)).then(res => {
          this.positionData = res.data.rows
        })
      },
      // 当选择关键作业类型时，影响关键作业内容
      chooseWorkType(item) {
        this.chooseWorkTypeCode = item.workTypeCode
        this.submitInfo.keyWorkCode = item.workTypeCode
        // 清除现有关键作业内容
        this.submitInfo.workContent = ''
        this.submitInfo.workRisk = ''
        this.workContentData = []
        this.searchWCode.Code = this.chooseWorkTypeCode
        // console.log('workTypeCode=' + this.chooseWorkTypeCode)
        getKeyWorkContentList(Object.assign(this.searchWCode)).then(res => {
          this.workContentData = res.data.rows
          // console.log('关键作业内容：')
          // console.log(res.data.rows)
        })
      },
      // 当选择关键作业内容时，影响风险作业等级
      chooseWorkContent(item) {
        // 清除现有风险作业等级
        this.submitInfo.workRisk = ''
        this.submitInfo.workRisk = item.workRisk
      },
      chooseEmployeeType(item) {
        this.submitInfo.employeeTypeCode = item.code
      },
      chooseAge(item) {
        console.log(item)
        this.submitInfo.ageCode = item.code
      },
      chooseWorkYears(item) {
        this.submitInfo.workYearsCode = item.code
      },
      chooseConsequences(item) {
        this.submitInfo.consequencesCode = item.code
      },
      chooseDepartment(item) {
        this.submitInfo.departmentCode = item.code
      },
      chooseCauseAnalysis(item) {
        this.submitInfo.clauseAnalysisCode = item.code
      },
      chooseLocation(item) {
        this.submitInfo.locationCode = item.locationCode
      },
      choosePosition(item) {
        this.submitInfo.positionCode = item.positionCode
      },
      chooseHse(item) {
        this.submitInfo.hseCode = item.code
      },
      chooseDangerType(item) {
        this.submitInfo.score = 0
        this.submitInfo.fine = 0
        this.submitInfo.violationTypeCode = item.violationTypeCode
        if (this.submitInfo.check_Type !== '基层队站-月检查' && this.submitInfo.check_Type !== '基层队站-周检查' && this.submitInfo.check_Type !== '岗位员工检查') {
          this.submitInfo.score = item.score
          this.submitInfo.fine = item.fine
        }
      },
      // 当单选改变时，设置违章性质，违章条款，记分，罚款为空
      // changeRadio() {
      //   this.submitInfo.violationType = ''
      //   this.submitInfo.score = 0
      //   this.submitInfo.fine = 0
      //   this.submitInfo.violationClause = ''
      //   this.submitInfo.description = ''
      //   this.vioClauseData = []
      // },
      handleVioCategoryClick(value, label, e) {
        // console.log('违章类别：')
        // console.log(e)
        if (e.triggerNode.$children.length === 0) {
          this.chooseVioCategoryId = e.triggerNode._props.value
          // console.log('id = ' + this.chooseVioCategoryId)
          this.queryEleCom.Id = this.chooseVioCategoryId
          this.submitInfo.violationCategory = e.triggerNode._props.title
          // 显示对应要素体系和对应安全沟通
          getElementList(Object.assign(this.queryEleCom)).then(res => {
            this.hseData = res.data.result
            // console.log(this.hseData)
            if (this.hseData.length) {
              if (this.submitInfo.violationCategory !== '其它') {
                this.submitInfo.hseElement = this.hseData[0].item
              }
            } else {
              this.chooseVioCategoryId = ''
              this.submitInfo.violationCategory = ''
              this.$message.warning('搜索违章类别不正确.请重新搜索！')
            }
          })
          getCommunicateList(Object.assign(this.queryEleCom)).then(res => {
            this.observeData = res.data.result
            if (this.submitInfo.violationCategory !== '其它') {
              this.submitInfo.observeComm = this.observeData[0].item1 + ';' + this.observeData[0].item2
            }
            // console.log(this.observeData)
            // console.log(res.data.result.item1)
          })
        } else {
          this.chooseVioCategoryId = ''
          this.submitInfo.violationCategory = ''
          // console.log('不是叶子结点噢')
          // 提醒用户这不是叶子节点
          this.showAlert()
        }
      },
      // 保存输入信息
      saveList() {
        console.log(this.submitInfo)
        if ([this.submitInfo.checkDate, this.submitInfo.organizationName, this.submitInfo.workSpecialty, this.submitInfo.erp, this.submitInfo.violationUserDepart,
          this.submitInfo.violationUserName, this.submitInfo.age, this.submitInfo.workYears, this.submitInfo.employeeType, this.submitInfo.position,
          this.submitInfo.causeAnalysis, this.submitInfo.directDepartment, this.submitInfo.potentialConsequence, this.submitInfo.violationClause, this.submitInfo.InspectionMethod,
          this.submitInfo.workItem].some(item => item === null || item === undefined)) {
          this.$message.warning('信息尚未完善，请完善后再提交')
        } else if (this.submitInfo.checkDate === '' || this.submitInfo.organizationName === '' || this.submitInfo.workSpecialty === '' || this.submitInfo.erp === '' || this.submitInfo.violationUserDepart === '' ||
          this.submitInfo.violationUserName === '' || this.submitInfo.age === '' || this.submitInfo.workYears === '' || this.submitInfo.employeeType === '' || this.submitInfo.position === '' ||
          this.submitInfo.violationType === '' || this.submitInfo.violationClause === '' || this.submitInfo.description === '' || this.submitInfo.violationCategory === '' || this.submitInfo.hseElement === '' ||
          this.submitInfo.causeAnalysis === '' || this.submitInfo.directDepartment === '' || this.submitInfo.potentialConsequence === '' || this.submitInfo.workItem === '' || this.submitInfo.location === '' ||
          this.submitInfo.InspectionMethod === '') {
          this.$message.warning('信息尚未完善，请完善后再提交')
        // } else if (!this.violationUserId) {
        //   this.$message.warning('请选择系统内人员！若无此人请选择用工性质为承包商员工')
        } else if (this.submitInfo.description === '无对应条款') {
          this.$message.warning('违章描述不允许为无对应条款')
        } else if (this.submitInfo.description === this.submitInfo.violationClause) {
          this.$message.warning('违章描述不允许和违章条款相同')
        } else if (!this.valId) {
          this.$message.error('身份证号格式错误')
        } else {
          this.saving = true
          if (this.addOrEdit === 0) {
            // const jobMajor = this.submitInfo.jobMajor
            addViolationInfo(this.submitInfo).then(response => {
              // 处理提交成功后的逻辑
              // console.log('新增成功！')
              console.log('response:', response)
              this.$message.success('保存违章成功！')
              this.saved = true
              this.addOrEdit = 1
              // console.log('response = ')
              // console.log(response.data)
              // 获取qhseXyViolationId
              const qhseXyViolationId = response.data
              this.submitInfo.qhseXyViolationId = qhseXyViolationId
              // console.log(qhseXyViolationId)
            })
              // eslint-disable-next-line handle-callback-err
              .catch(error => {
                // 处理提交失败后的逻辑
                // console.log('新增失败！')
                this.$message.error('保存违章失败！')
              })
              .finally(() => {
                // 不管成功失败都要取消loading状态
                this.saving = false
              })
          } else {
            // 实现编辑功能
            editViolationInfo(this.submitInfo).then(response => {
              // 处理提交成功后的逻辑
              // console.log('编辑成功！')
              this.$message.success('修改违章成功！')
              this.addOrEdit = 1
            })
              // eslint-disable-next-line handle-callback-err
              .catch(error => {
                // 处理提交失败后的逻辑
                // console.log('编辑失败！')
                this.$message.error('修改违章失败！')
              })
              .finally(() => {
                // 不管成功失败都要取消loading状态
                this.saving = false
              })
          }
        }
      },
      onSubmit2() {
        this.submitInfo.push = true
        // console.log('this.submitifo', this.submitInfo)
        // console.log(this.submitInfo)
        if ([this.submitInfo.checkDate, this.submitInfo.organizationName, this.submitInfo.workSpecialty, this.submitInfo.erp, this.submitInfo.violationUserDepart,
          this.submitInfo.violationUserName, this.submitInfo.age, this.submitInfo.workYears, this.submitInfo.employeeType, this.submitInfo.position,
          this.submitInfo.causeAnalysis, this.submitInfo.directDepartment, this.submitInfo.potentialConsequence, this.submitInfo.violationClause,
          this.submitInfo.workItem].some(item => item === null || item === undefined)) {
          this.$message.warning('信息尚未完善，请完善后再提交')
        } else if (this.submitInfo.checkDate === '' || this.submitInfo.organizationName === '' || this.submitInfo.workSpecialty === '' || this.submitInfo.erp === '' || this.submitInfo.violationUserDepart === '' ||
          this.submitInfo.violationUserName === '' || this.submitInfo.age === '' || this.submitInfo.workYears === '' || this.submitInfo.employeeType === '' || this.submitInfo.position === '' ||
          this.submitInfo.violationType === '' || this.submitInfo.violationClause === '' || this.submitInfo.description === '' || this.submitInfo.violationCategory === '' || this.submitInfo.hseElement === '' ||
          this.submitInfo.causeAnalysis === '' || this.submitInfo.directDepartment === '' || this.submitInfo.potentialConsequence === '' || this.submitInfo.workItem === '' || this.submitInfo.location === '') {
          this.$message.warning('信息尚未完善，请完善后再提交')
        // } else if (!this.violationUserId) {
        //   this.$message.warning('请选择系统内人员！若无此人请选择用工性质为承包商员工')
        } else if (this.submitInfo.description === '无对应条款') {
          this.$message.warning('违章描述不允许为无对应条款')
        } else if (this.submitInfo.description === this.submitInfo.violationClause) {
          this.$message.warning('违章描述不允许和违章条款相同')
        } else if (!this.valId) {
          this.$message.error('身份证号格式错误')
        } else {
          this.saving1 = true
          if (this.addOrEdit === 0) {
            // const jobMajor = this.submitInfo.jobMajor
            addViolationInfo(this.submitInfo).then(response => {
              // 处理提交成功后的逻辑
              // console.log('新增成功！')
              console.log('response:', response)
              this.$message.success('保存违章并推送成功！')
              this.saved = true
              this.addOrEdit = 1
              // console.log('response = ')
              // console.log(response.data)
              // 获取qhseXyViolationId
              const qhseXyViolationId = response.data
              this.submitInfo.qhseXyViolationId = qhseXyViolationId
              this.submitInfo.push = false
              // console.log(qhseXyViolationId)
            })
              // eslint-disable-next-line handle-callback-err
              .catch(error => {
                // 处理提交失败后的逻辑
                // console.log('新增失败！')
                this.$message.error('保存违章并推送失败！')
                this.submitInfo.push = false
              })
              .finally(() => {
                // 不管成功失败都要取消loading状态
                this.saving1 = false
                this.submitInfo.push = false
              })
          } else {
            // 实现编辑功能
            editViolationInfo(this.submitInfo).then(response => {
              // 处理提交成功后的逻辑
              // console.log('编辑成功！')
              this.$message.success('修改违章并推送成功！')
              this.addOrEdit = 1
            })
              // eslint-disable-next-line handle-callback-err
              .catch(error => {
                // 处理提交失败后的逻辑
                // console.log('编辑失败！')
                this.$message.error('修改违章并推送失败！')
              })
              .finally(() => {
                // 不管成功失败都要取消loading状态
                this.saving1 = false
              })
          }
        }
      },
      // 新增，清空全部内容
      onSubmit() {
        console.log(this.submitInfo)
        this.saved = false
        this.addOrEdit = 0
        this.fileList = []
        this.hseData = []
        this.observeData = []
        this.submitInfo = {
          ...this.submitInfo,
          enterSys: '公司隐患违章系统',
          qhseXyViolationId: '',
          check_Type: this.dataProp.check_Type,
          checkTypeCode: this.dataProp.checkTypeCode,
          violationUserId: '', // 违章人员id
          violationUserName: '', // 违章人员姓名
          violationUserDepart: '', // 违章岗位
          erp: '', // erp号
          enterTime: moment(new Date()).format('YYYY-MM-DD HH:mm:ss').replace(' ', 'T'),
          position: '', // 违章岗位
          age: '', // 年龄
          workYears: '', // 工龄
          employeeType: '', // 用工性质
          InspectionMethod: '', // 检查方式
          score: 0, // 记分
          fine: 0, // 罚款
          violationTypeCategory: '', // 通用违章 or 专业违章
          violationType: '', // 违章性质
          violationClause: undefined, // 违章条款
          description: '', // 违章描述
          violationCategory: '', // 违章类别
          hseElement: '', // 对应要素体系
          observeComm: '', // 对应安全沟通
          causeAnalysis: '', // 原因分析
          directDepartment: '', // 归属部门
          potentialConsequence: '', // 可能后果
          files: [] // 图片文件
        }
        this.enterTime = moment(new Date()).format('YYYY-MM-DD HH:mm:ss')
      },
      cancel() {
        this.$emit('cancel')
      },
      handleOrganNameClick(value, label, e) {
        if (value && label) {
          // 获取当前选择的单位的节点对象
          if (Array.isArray(label) && label.length > 0) {
            const selectedLabels = label.map(item => item.label)
            const selectedValues = value
            const lastSelectedLabel = selectedLabels[selectedLabels.length - 1]
            const lastSelectedValue = selectedValues[selectedValues.length - 1]
            this.submitInfo.organizationName = lastSelectedLabel // 将多个单位的标签用逗号分隔
            this.submitInfo.organizationId = lastSelectedValue // 将多个单位的值用逗号分隔
            // console.log(this.submitInfo.organizationName)
            // console.log(this.submitInfo.organizationId)
          } else {
            console.error('未选择单位或选择不正确')
          }
        }
      },
      moment,
      getCurrentData() {
        return new Date().toLocaleDateString()
      },
      // 日期选择器的change方法
      onChangeTime(dates, dateStrings) {
        // const date = new Date(dateStrings)
        // const year = date.getFullYear() // 获取年份
        // const month = ('0' + (date.getMonth() + 1)).slice(-2) // 获取月份，需要补 0
        // const day = ('0' + date.getDate()).slice(-2) // 获取日期，需要补 0
        // this.submitInfo.checkDate = `${year}-${month}-${day}` // 将日期赋值为年-月-日格式
        // console.log('this.submitInfo.checkDate = ' + this.submitInfo.checkDate)
        const enterDate = moment(this.enterTime, 'YYYY-MM-DD HH:mm:ss')
        // const date2 = moment(time2, 'YYYY-MM-DD HH:mm:ss')
        const differenceInDays = enterDate.diff(dates, 'days')
        const differenceInSeconds = enterDate.diff(dates, 'seconds')
        if (differenceInSeconds < 0) {
          this.$message.warning('检查时间不能晚于录入时间')
          this.checkTime = enterDate.subtract(1, 'seconds')
          this.submitInfo.checkDate = this.checkTime.format('YYYY-MM-DD HH:mm:ss')
        } else if (differenceInDays >= this.$constants.timeInterval) {
          this.$message.warning('检查时间与录入时间不能超过' + this.$constants.timeInterval + '天')
          this.checkTime = enterDate.subtract(1, 'seconds')
          this.submitInfo.checkDate = this.checkTime.format('YYYY-MM-DD HH:mm:ss')
        } else {
          this.submitInfo.checkDate = dateStrings.replace(' ', 'T')
        }
      },
      sexFilter(sex) {
        // eslint-disable-next-line eqeqeq
        const values = this.sexDictTypeDropDown.filter((item) => item.code == sex)
        if (values.length > 0) {
          return values[0].value
        }
      },
      handleOk() {
        this.$refs.table.refresh()
      },
      onSelectChange(selectedRowKeys, selectedRows) {
        this.selectedRowKeys = selectedRowKeys
        this.selectedRows = selectedRows
      }
    }
  }
</script>
<style lang="less" scoped>
.readonly-radio {
  pointer-events: none; /* 禁用交互 */
  color: #000; /* 设置文本颜色，可根据需求自定义 */
}
  .table-operator {
    margin-bottom: 18px;
  }
  button {
    margin-right: 8px;
  }
  .search-row {
    display: flex;
    align-items: center;
  }

  .search-buttons {
    display: flex;
    justify-content: flex-end;
  }
  .ant-form-item-label {
    width: 800px; /* 将标签宽度改为 100 像素 */
  }
    .spinner {
    border: 4px solid #f3f3f3;
    border-top: 4px solid #3498db;
    border-radius: 50%;
    width: 48px;
    height: 48px;
    animation: spin 2s linear infinite;
    margin: 20px auto;
  }

  @keyframes spin {
    0% {
      transform: rotate(0deg);
    }
    100% {
      transform: rotate(360deg);
    }
  }
  .custom-divider.ant-divider-horizontal {
    border-bottom-width: 4px; /* 设置分割线的粗细 */
  }
</style>
